home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 12312 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.5 KB  |  82 lines

  1. Newsgroups: comp.lang.c
  2. Path: alisa.org!wjjr
  3. From: wjjr@alisa.org (John J. Rushford)
  4. Subject: Re: Returning string from function (how?)
  5. X-Newsreader: TIN [version 1.2 PL2]
  6. Organization: My place on the Front Range.
  7. Message-ID: <Dp3AB5.FEu@alisa.org>
  8. References: <4jj4hh$m9n@news.xs4all.nl>
  9. Date: Sat, 30 Mar 1996 16:40:17 GMT
  10.  
  11. Jordan (jordan@xs4all.nl) wrote:
  12. : Hi all, i'm trying to get a string returned  from a function, but it's not
  13. : working as i planed.
  14. : Does anyone have some ideas?
  15.  
  16.  
  17. : something like this, but then working ;)
  18.  
  19. : /*****************************************/
  20.  
  21. : char s;
  22.  
  23. : char get_str(void);
  24.  
  25. : main()
  26. : {
  27. :    s = get_str();
  28.  
  29. :    printf("%s", s);
  30. : }
  31.  
  32. : char get_str(void)
  33. : {
  34. :    int i;
  35. :    char ch, string;
  36.  
  37. :    i=0;    
  38. :    printf("Enter a string: ");
  39. :    while((ch = getchar()) != '\n' && i < MAX)
  40. :       string[i++] = ch;
  41. :    string[i] = '\0';
  42.  
  43. :    return string;
  44. : }
  45.  
  46. I don't see where you are allocating space for 'string'.  Also, when the
  47. function get_str() returns, the local variable 'string' is lost from the
  48. stack.  How about:
  49.  
  50. #define MAX 80
  51.  
  52. char string[MAX];   /* global string with space allocated. */
  53.  
  54. char * 
  55. get_str ()
  56. {
  57.     int i = 0;
  58.     char ch;
  59.  
  60.     printf ("Enter a string: ");
  61.     while ((ch = getchar ()) != '\n' && i < MAX) 
  62.     string[i++] = ch;
  63.     string[i] = '\0';
  64.  
  65.     return string;
  66. }
  67.  
  68. main ()
  69. {
  70.     char * s;
  71.     
  72.     s = get_str ();
  73.     printf ("%s", s);
  74. }
  75.  
  76. regards
  77. -- 
  78. John J. Rushford              
  79. Westminster, Colorado___/\_/\_
  80. wjjr@alisa.org (alisa.org is powered by FreeBSD)
  81.  
  82.